package controllers

import (
	"cronjob/libs"
	"cronjob/models"
	"strings"
	"time"
)

// 管理员管理
type UserController struct {
	BaseController
}

//编辑
func (this *UserController) Edit() {
	this.Data["pageTitle"] = "资料修改"

	uid := this.userID

	ainfo, _ := models.AdminGetById(uid)
	row := make(map[string]interface{})
	row["id"] = ainfo.Id
	row["login_name"] = ainfo.LoginName
	row["real_name"] = ainfo.RealName
	row["phone"] = ainfo.Phone
	row["email"] = ainfo.Email

	this.Data["admin"] = row
	this.display()
}

//
func (this *UserController) AjaxSave() {
	uid := this.userID

	ainfo, _ := models.AdminGetById(uid)

	ainfo.UpdateTime = time.Now().Unix()
	ainfo.UpdateId = this.userID
	ainfo.LoginName = strings.TrimSpace(this.GetString("login_name"))
	ainfo.RealName = strings.TrimSpace(this.GetString("real_name"))
	ainfo.Phone = strings.TrimSpace(this.GetString("phone"))
	ainfo.Email = strings.TrimSpace(this.GetString("email"))

	reset_pwd := this.GetString("reset_pwd")
	if reset_pwd == "1" {

		password_old := strings.TrimSpace(this.GetString("password_old"))
		if password_old == "" {
			this.ajaxMsg("原密码不能为空", MSG_ERR)
		}

		if ainfo.Password != libs.MD5([]byte(password_old+ainfo.Salt)) {
			this.ajaxMsg("原始密码不正确", MSG_ERR)
		}

		password_new1 := strings.TrimSpace(this.GetString("password_new1"))
		password_new2 := strings.TrimSpace(this.GetString("password_new2"))

		if password_new1 != password_new2 {
			this.ajaxMsg("修改密码与确认密码不相等", MSG_ERR)
		}

		newPassword, salt := libs.Password(4, password_new1)

		ainfo.Password = newPassword
		ainfo.Salt = salt

	}

	ainfo.UpdateTime = time.Now().Unix()
	ainfo.UpdateId = this.userID

	if err := ainfo.Update(); err != nil {
		this.ajaxMsg("修改失败", MSG_ERR)
	}

	this.ajaxMsg("修改", MSG_OK)
}
